﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using UCL.Data;
using UCL.Forms;

namespace UCL.Forms.Components
{
    public partial class frmLinkEdit : Form
    {
        public string MainName { get; set; }
        public string HostUri { get; set; }
        SoExplorer.ComDataHelper adh;
        public frmLinkEdit()
        {
            InitializeComponent();
        }

        private void frmLinkEdit_Load(object sender, EventArgs e)
        {
            adh = new SoExplorer.ComDataHelper();
            this.FormLoad();
        }

        public void FormLoad()
        {
            if (!string.IsNullOrEmpty(this.HostUri))
            {
                tbName.Text = this.HostUri.Split('\\').Last();
                tbHostUri.Text = this.HostUri;
            }
            if (string.IsNullOrEmpty(MainName)) return;
            DataModule dm = new DataModule("tExplorerFavorite", adh);
            if (!dm.DBH.Exists("", string.Format("Name='{0}'", this.MainName)))
            {
                MessageBox.Show("记录不存在");
                return;
            }
            DataTable dtItem = dm.DBH.SelectDataTable("", string.Format("Name='{0}'",this.MainName));
            tbName.Text = dtItem.GetValue<string>("Name");
            tbHostUri.Text = dtItem.GetValue<string>("HostUri");
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            DataModule dm = new DataModule("tExplorerFavorite", adh);
            dm.AddParam("Name", tbName.Text, "名称未填写");
            dm.AddParam("HostUri", tbHostUri.Text, "地址路径未填写");
            if (tbName.TextLength > 0 && string.IsNullOrEmpty(this.MainName) && dm.DBH.Exists("", string.Format("Name='{0}'",tbName.Text))) dm.MessageSet.Add(string.Format("名称[{0}]的记录已存在!",tbName.Text));
            if (dm.MessageSet.Count > 0)
            {
                MessageBox.Show(dm.GetError());
                return;
            }
            bool result = string.IsNullOrEmpty(this.MainName) ? dm.Insert() : dm.Update(string.Format("Name='{0}'",this.MainName));
            MessageBox.Show(result ? "保存成功" : dm.GetError());
            if (result)
            {
                ucExplorer uc = (ucExplorer)this.Tag;
                uc.LoadLinks();
                this.Close();
            }
        }
    }
}
